// ==UserScript==
// @name         途家图片批量下载
// @namespace    http://tampermonkey.net/
// @version      2025-04-20
// @description  try to take over the world!
// @author       You
// @match        https://m.tujia.com/detail/*.htm?*
// @match        https://m.tujia.com/detail/*.htm
// @match        https://m.tujia.com/detail/*.htm*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tujia.com
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js
// @require      https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // 定义目标URL前缀
    const TARGET_PREFIX = 'https://m.tujia.com/bnbapp-node-h5/h5/house/gethouse/v3/bnb?refPid=';
    const IMAGE_HOST = 'https://pic.tujia.com';
    const GD_LOCATION = 'https://restapi.amap.com/v3/geocode/regeo?key=602951d65739a456ecf65def99752f77&location='
    let HOUSE_Id
    let imageList
    let cityName
    const { unProxy } = ah.proxy({
        onRequest: (config, handler) => {
            handler.next(config);
        },
        onResponse: (response, handler) => {
            if (response.config.url.startsWith(TARGET_PREFIX)) {
                let res = JSON.parse(response.response);
                console.log(res)
                HOUSE_Id = res.data.houseId
                imageList = res.data.mainPart.topModule.housePicture.housePics
                // 定位
                if (!res.data.mainPart.topModule.navigation.longitude || !res.data.mainPart.topModule.navigation.latitude) {
                    cityName = res.data.mainPart.topModule.navigation.title
                } else {
                    $.get({
                        url: `${GD_LOCATION}${res.data.mainPart.topModule.navigation.longitude},${res.data.mainPart.topModule.navigation.latitude}`,
                        type:'get',
                        dataType: 'json',
                        success(locationRes){
                            cityName = locationRes.regeocode.addressComponent.city
                            console.log(locationRes.regeocode.addressComponent)
                        }
                    })
                }
                console.log(cityName)
            }
            handler.next(response);
        }
    });
    // 页面卸载时解除拦截
    window.addEventListener('beforeunload', () => {
        unProxy();
    });
    $(document).ready(function() {
        // 获取ID
        const id = location.href.split('https://m.tujia.com/detail/')[1].split(".")[0];
        // 创建并配置按钮
        const $button = $('<button>', {
            id: 'topRightBtn',
            text: '批量下载图片',
            css: {
                position: 'fixed',
                right: '0px',
                top: '80px',
                padding: '12px 24px',
                backgroundColor: '#2196F3',
                color: 'white',
                border: 'none',
                borderRadius: '5px',
                cursor: 'pointer',
                fontSize: '16px',
                zIndex: 1000
            },
            click: function() {
                console.log('即将执行批量下载！');
                for(let index in imageList) {
                    setTimeout(() => {
                        const src = IMAGE_HOST + imageList[index].originUrl;
                        // 跳过无src的元素
                        if (!src) return;

                        const fileName = `${cityName}_${HOUSE_Id}_${index*1 + 1}`

                    // 下载图片（处理跨域问题）
                    downloadImageWithFetch(src, fileName);
                    }, index * 200)
                }
            }
        });
        // 插入到页面
        $('body').prepend($button);
    })
    function downloadImageWithFetch(src, fileName) {
        console.log(src, fileName)

        fetch(src, { mode: 'cors' })
            .then(response => {
            if (!response.ok) throw new Error('网络错误');
            return response.blob();
        })
            .then(blob => {
            const downloadUrl = URL.createObjectURL(blob);
            const $a = $('<a>', {
                href: downloadUrl,
                download: fileName || 'downloaded_image'
            });
            $('body').append($a);
            $a[0].click();
            $a.remove();
            URL.revokeObjectURL(downloadUrl);
        })
            .catch(error => {
            console.error('下载失败:', error);
        });
    }
})();